<?php

namespace App\Http\Controllers\Back;

use App\Models\Back\Brand;
use App\Tool\Tool;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/*
 * 品牌控制器类
 */
class BrandController extends Controller
{
	/*
	 * 设置品牌
	 * get请求显示页面
	 * post请求添加品牌或修改品牌信息
	 */
	public function set (Request $request, $id = 0)
	{
		if ($request->isMethod('post')) {

			//实例化模型
			$BrandModel = new Brand();
			//表单验证
			$BrandModel->setValidator($request->all());

			//logo存在且有效时，上传logo
			if ($request->hasFile('logo') && $request->file('logo')->isValid()) {
				$logoPath = $BrandModel->logoUpload($request);
				if ($logoPath) {
					//生成缩略图
					$BrandModel->logoThumb($logoPath);
					$request->logoPath = $logoPath;
				} else {
					$request->logoPath = '';
				}
			}

			//更新数据库
			$res = $BrandModel->set($request);

			if ($res) {
				return redirect()->route('brand.list');
			} else {
				return back()->withInput();
			}
		} else {
			if ($id) {
				//获取单条品牌信息
				$brand = Brand::find($id);
				return view('back.brand.set', ['brand' => $brand]);
			} else {
				return view('back.brand.set');
			}
		}
	}



	/*
	 * 展示品牌列表
	 * post提交过来为删除操作
	 */
	public function show (Request $request, $field = 'sort_number', $order = 'asc')
	{
		$brandModel = new Brand();
		if ($request->isMethod('post')) {
			//验证
			$brandModel->deleteValidator($request->all());
			//删除
			$brandModel->deleteBrand($request->input('selected'));
			return back();
		} else {
			//取排序后的结果集
			$brandCollection = $brandModel->brandOrder($field, $order);
			//处理页面class和url问题
			$list = Tool::sortClass($field, $order);

			$list['brandCollection'] = $brandCollection;
			return view('back.brand.list', $list);
		}
	}

	/*
	 * 品牌搜索
	 */
	public function search(Request $request)
	{
		$brandModel = new Brand();
		$brandCollection = $brandModel->searchBrand($request->all());
		return view('back.brand.list', ['brandCollection' => $brandCollection]);
	}
}
